/**
 * @author 雷明浩
 * @date 2025/5/29 11:16
 */
public class SortList {
    // leetcode 排序链表
    // https://leetcode.cn/problems/sort-list/?envType=study-plan-v2&envId=top-100-liked
    public ListNode sortList(ListNode head) {
        if (head == null ||head.next == null) return head;
        ListNode slow = head;
        ListNode fast = head;
        ListNode prev = null;
        while (fast != null && fast.next != null) {
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        prev.next = null;
        ListNode leftList = sortList(head);
        ListNode rightList = sortList(slow);
        return merge(leftList, rightList);
    }

    private ListNode merge(ListNode head1, ListNode head2) {
        ListNode phead = new ListNode();
        ListNode cur = phead;
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        while (cur1 != null && cur2 != null) {
            if(cur1.val <cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            }else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        if (cur1 != null) {
            cur.next = cur1;
        }
        if (cur2 != null) {
            cur.next = cur2;
        }
        return phead.next;
    }
}